#include "StdAfx.h"
#include "ItemIDList.h"

CItemIDList::CItemIDList(void)
{
}

CItemIDList::~CItemIDList(void)
{
}

LPITEMIDLIST CItemIDList::Copy(LPITEMIDLIST lpSrc)
{
	UINT uSz = GetItemIDListSize(lpSrc);
	IMalloc* lpMalloc = NULL;
	SHGetMalloc(&lpMalloc);
	void* lpTarget = lpMalloc->Alloc(uSz);
	lpMalloc->Release();
	memcpy(lpTarget, lpSrc, uSz);
	return (LPITEMIDLIST)lpTarget;
}

UINT CItemIDList::GetItemIDListSize(LPITEMIDLIST lpItem)
{
	UINT uSz = 0;
	LPITEMIDLIST lpTemp = lpItem;
	while(lpTemp->mkid.cb != 0)
	{
		uSz += lpTemp->mkid.cb;
		lpTemp = (LPITEMIDLIST)((char*)lpTemp + lpTemp->mkid.cb);
	}
	uSz += sizeof(ITEMIDLIST);
	return uSz;
}

void CItemIDList::Delete(LPITEMIDLIST lpItem)
{
	IMalloc* lpMalloc = NULL;
	SHGetMalloc(&lpMalloc);
	lpMalloc->Free((void*)lpItem);
	lpMalloc->Release();
}

string CItemIDList::GetPath(LPITEMIDLIST lpItem)
{
	string strPath("/");
	if(lpItem)
	{
		LPITEMIDLIST lpTmp = lpItem;
		while(lpTmp->mkid.cb != 0)
		{
			strPath.append((const char*)&lpTmp->mkid.abID[0]);
			strPath.append("/");
			lpTmp = (LPITEMIDLIST)((char*)lpTmp + lpTmp->mkid.cb);
		}
	}
	return strPath;
}

LPITEMIDLIST CItemIDList::Create(string strDirectoryName)
{
	USHORT uLen = sizeof(USHORT) + strDirectoryName.length() + 1;
	uLen += (4 - uLen % 4);
	USHORT uTotalLen = uLen + sizeof(ITEMIDLIST);
	IMalloc* lpMalloc = NULL;
	SHGetMalloc(&lpMalloc);
	char* lpTarget = (char*)lpMalloc->Alloc(uTotalLen);
	lpMalloc->Release();
	memset(lpTarget, 0, uTotalLen);
	memcpy(lpTarget, &uLen, sizeof(USHORT));
	memcpy(lpTarget + sizeof(USHORT), strDirectoryName.c_str(), strDirectoryName.length());
	return (LPITEMIDLIST)lpTarget;
}

LPITEMIDLIST CItemIDList::Connect(LPITEMIDLIST lpItem1, LPITEMIDLIST lpItem2)
{
	if(!lpItem1)
		return Copy(lpItem2);

	if(!lpItem2)
		return Copy(lpItem1);

	UINT uItemLen1 = GetItemIDListSize(lpItem1) - sizeof(ITEMIDLIST);
	UINT uItemLen2 = GetItemIDListSize(lpItem2);
	IMalloc* lpMalloc = NULL;
	SHGetMalloc(&lpMalloc);
	char* lpTarget = (char*)lpMalloc->Alloc(uItemLen1 + uItemLen2);
	lpMalloc->Release();
	memcpy(lpTarget, lpItem1, uItemLen1);
	memcpy(lpTarget + uItemLen1, lpItem2, uItemLen2);
	return (LPITEMIDLIST)lpTarget;
}
